<?php

declare(strict_types=1);

namespace App\Controller\Admin\V1\Order;

use App\Constants\Payment\PaymentCode;
use App\Controller\Admin\V1\Controllers;
use App\Exception\InternalException;
use App\Factory\Refund\Factory;
use App\Model\App\App;
use App\Utils\Other\Office\Excel\Export;
use Hyperf\Database\Model\Relations\HasMany;
use Hyperf\Database\Model\Relations\HasOne;
use Hyperf\DbConnection\Db;
use Psr\Http\Message\ResponseInterface;
use App\Request\Orders\Order as OrderRequest;
use App\Services\Orders\Order as OrderServices;
use function Hyperf\Translation\__;

class Order extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = OrderRequest::class;

    public function __construct(
        OrderServices $orderServices
    )
    {
        parent::__construct();
        $this->services = $orderServices;
    }

    /**
     * 订单分页
     * @return ResponseInterface
     * @throws \Throwable
     */
    public function page():ResponseInterface
    {
        $query = $this->query();

        [$field, $order] = $this->orderMap();
        $page = $this->services
            ->search($query)
            ->with(['goods', 'declares'])
            ->orderBy($field, $order)
            ->paginate($this->getLimit());

        return success(compact('page'));
    }

    /**
     * 订单申报
     * @param int $id
     * @return ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function declares(int $id):ResponseInterface
    {
        /** @var \App\Model\Orders\Order $model */
        $model = $this->services
            ->with(['declares'])
            ->findOrFail($id);

        $model->declaration(false);

        return success();
    }

    /**
     * 万里牛
     * @param int $id
     * @return ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function erp(int $id):ResponseInterface
    {
        /** @var \App\Model\Orders\Order $model */
        $model = $this->services->findOrFail($id);

        $model->pushErp(true);

        return success();
    }

    /**
     * 重新回调
     * @param int $id
     * @return ResponseInterface
     */
    public function notify(int $id):ResponseInterface
    {
        /** @var \App\Model\Orders\Order $model */
        $model = $this->services->findOrFail($id);

        $model->notify();

        return success();
    }
}
